const cloud = require('wx-server-sdk')
const utils_distri_free_amou = require('./utils_AutoDistributeFreeAmou.js')
cloud.init({env: 'evn-cloud-a-4gf1q6iy9df62d73'})
const db = cloud.database()
const _ = db.command
const MAX_LIMIT = 100

const numberFormat = n => {
  n = n.toString()
  return n[1] ? n : `0${n}`
}
const dateFormatter = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const dateStr = `${[year, month, day].map(numberFormat).join('-')}`
  return dateStr
}

/**根据规则自动生成当日放生额,位置： 首页 --> 生成按钮 */
const autoDistributeFreeAmount = async (event) => {
  console.log('\n\n\n开始自动分配放生额...')
  const totaAmount = event.totalFreeAmount
  //检查总余额合法性,true：合法，false：非法
  const queryResult = await utils_distri_free_amou.checkTotalBalanceLegally(totalFreeAmount)
  if(!queryResult.isLegally){
    console.error('总余额不足.')
    return {code: 2001, errMsg: '总余额不足.'}
  }
  const waitAllotTotalAmount = totaAmount - queryResult.sumFreeAmount
  const avgAmount = await getAvgAmount(waitAllotTotalAmount)

}

/**根据id更新金额,位置：首页 -->模态框 --> 确定 */
const updateAmountById = async freeCap => {
  const resultById = await db.collection("freeCaptiveDetails").where({_id: freeCap._id}).get({})
  if(resultById.data.length != 1){
    return ;
  }
  const dbFreeAmount = Number(resultById.data[0].freeAmount)
  const dbBalance = Number(resultById.data[0].balance)
  const freeAmount = Number(freeCap.freeAmount)
  const plus_balance = dbBalance + dbFreeAmount - freeAmount
  //console.log('将更新的余额：', plus_balance,'将更新的放生额：', freeAmount)
  try {
    const result = await db.collection('freeCaptiveDetails').doc(freeCap._id).update({
      data: {
        //放生额加
        freeAmount: Number(freeAmount.toFixed(2)),
        //余额减
        balance: Number(plus_balance.toFixed(2))
      },
    })
    return result
  } catch(e) {
    console.error(e)
  }
}

const main = async (event) => {
  const reqType = event.reqType
  switch(reqType){
    case "updateAmountById":
      return await updateAmountById(event)
    case "autoDistributeFreeAmount":
      return await autoDistributeFreeAmount(event)
    default:
      return { data: null, errMsg: '请求类型错误'}
  }
}
module.exports = {
  main
}